package com.yihuier.yihuier.Controller.Common;

import com.yihuier.yihuier.Entity.MeetingManager.MeetingData;
import com.yihuier.yihuier.Service.Common.FileUploadService;
import com.yihuier.yihuier.Service.UserManager.UserService;
import com.yihuier.yihuier.Util.ImageUtil;
import com.yihuier.yihuier.Util.ResponseMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.websocket.server.PathParam;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashMap;

@RestController
@RequestMapping("/Common/FileUpload/")
public class FileUploadController {

    @Value("${yihuier.fileupload.maxfilesize}")
    private long MAX_UPLOAD_FILE_SIZE;

    @Value("${local.path}")
    private String localRoute;

    @Value("${yihuier.fileupload.dir}")
    private Path SAVE_ROOT_DIR;

    @Value("${yihuier.fileupload.dir.user_header_pic}")
    private Path USER_PIC_DIR;

    @Value("${yihuier.fileupload.dir.meeting_room_pic}")
    private Path ROOM_PIC_DIR;

    @Value("${yihuier.fileupload.dir.meeting_file}")
    private Path MEETING_FILE_DIR;

    @Value("${yihuier.fileupload.dir.meeting_recording}")
    private Path MEETING_RECORDING_DIR;

    @Value("${yihuier.fileupload.image.width}")
    private int DEFAULT_IMAGE_WIDTH;

    @Value("${yihuier.fileupload.image.height}")
    private int DEFAULT_IMAGE_HEIGHT;

    @Autowired
    private UserService userService;

    @Autowired
    private FileUploadService fileUploadService;

    @PostMapping("upload.do")
    public ResponseMessage upload(@PathParam("id") int id, @PathParam("file") MultipartFile file, @PathParam("type") String type){
        if (id == 0){
            return new ResponseMessage(ResponseMessage.ERROR,"请求ID错误");
        }
        if (file.isEmpty()){
            return new ResponseMessage(ResponseMessage.ERROR,"上传文件为空");
        }

        //先得到文件的输入流
        InputStream tempFileInputStream;
        try {
            tempFileInputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("获取文件输入流失败");
            return new ResponseMessage(ResponseMessage.ERROR,"文件无法读取");
        }
        //获取文件名
        String md5FileName = fileUploadService.getFileName(tempFileInputStream);
        String filename = file.getOriginalFilename();

        if (md5FileName == null){
            //文件名解析错误
            return new ResponseMessage(ResponseMessage.ERROR,"文件上传出错，请稍后再试");
        }

        HashMap<String,String> resultFileMap = new HashMap<>();

        if (type.equals("user_header_pic")){
            //请求上传文件：用户头像
            //id值为用户id
            if (!fileUploadService.findFileIsExist(USER_PIC_DIR,md5FileName + ".jpg")){
                //如果文件不存在，保存
                try(InputStream in = file.getInputStream()) {
                    //改变分辨率就保存了
                    ImageUtil.changeImagesResolution(in,USER_PIC_DIR.resolve(md5FileName + ".jpg"),DEFAULT_IMAGE_WIDTH,DEFAULT_IMAGE_HEIGHT,false);
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
                }
            }
            if (fileUploadService.updateUserHeaderPic(id,USER_PIC_DIR.resolve(md5FileName + ".jpg").toString())){
                resultFileMap.put("path",localRoute +  "/file/user_header_pic/" + md5FileName + ".jpg");
                return new ResponseMessage(ResponseMessage.SUCCESS
                        ,"上传成功"
                        , resultFileMap.get("path"));
            }else {
                return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
            }
        }else if(type.equals("meeting_room_pic")){
            //请求上传文件：会议室图片
            //id值为会议室id
            if (!fileUploadService.findFileIsExist(ROOM_PIC_DIR,md5FileName + ".jpg")){
                //如果文件不存在，保存
                try(InputStream in = file.getInputStream()) {
                    //改变分辨率就保存了
                    ImageUtil.changeImagesResolution(in,ROOM_PIC_DIR.resolve(md5FileName + ".jpg"),DEFAULT_IMAGE_WIDTH,DEFAULT_IMAGE_HEIGHT,false);
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
                }
            }
            if (fileUploadService.updateRoomPic(id,ROOM_PIC_DIR.resolve(md5FileName + ".jpg").toString())){
                resultFileMap.put("path",localRoute +  "/file/meeting_room_pic/" + md5FileName + ".jpg");
                return new ResponseMessage(ResponseMessage.SUCCESS
                        ,"上传成功"
                        ,resultFileMap.get("path"));
            }else {
                return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
            }
        }else if(type.equals("meeting_file")){
            //请求上传文件：会议文件
            //id值为会议id
            String filetype = filename.substring(filename.lastIndexOf(".") + 1);
            if (!fileUploadService.findFileIsExist(MEETING_FILE_DIR,md5FileName + filetype)){
                //如果文件不存在，保存
                try {
                    file.transferTo(MEETING_FILE_DIR.resolve(md5FileName + filetype).toFile());
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
                }
            }
            MeetingData meetingData = new MeetingData();
            meetingData.setData_meeting_id(id);
            meetingData.setData_name(filename);
            meetingData.setData_type((short)1);
            meetingData.setData_address(MEETING_FILE_DIR.resolve(md5FileName + filetype ).toString());
            if (fileUploadService.uploadMeetingFile(meetingData)){
                resultFileMap.put("path",localRoute +  "/file/meeting_file/" + md5FileName + filetype);
                return new ResponseMessage(ResponseMessage.SUCCESS
                        ,"上传成功"
                        ,resultFileMap.get("path"));
            }else {
                return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
            }
        }else if(type.equals("meeting_recording")){
            //请求上传文件：会议录音
            //id值为会议id
            String filetype = filename.substring(filename.lastIndexOf(".") + 1);
            if (!fileUploadService.findFileIsExist(MEETING_RECORDING_DIR,md5FileName + filetype)){
                //如果文件不存在，保存
                try {
                    file.transferTo(MEETING_RECORDING_DIR.resolve(md5FileName + filetype).toFile());
                } catch (IOException e) {
                    e.printStackTrace();
                    return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
                }
            }
            //文件不存在，先保存
            MeetingData meetingData = new MeetingData();
            meetingData.setData_meeting_id(id);
            meetingData.setData_name(filename);
            meetingData.setData_type((short)2);
            meetingData.setData_address(MEETING_RECORDING_DIR.resolve(md5FileName + filetype).toString());
            if (fileUploadService.uploadMeetingFile(meetingData)){
                resultFileMap.put("path",localRoute +  "/file/meeting_recording/" + md5FileName + filetype);
                return new ResponseMessage(ResponseMessage.SUCCESS
                        ,"上传成功"
                        ,resultFileMap.get("path"));
            }else {
                return new ResponseMessage(ResponseMessage.ERROR,"上传失败");
            }
        }else {
            //类型值错误，返回错误消息
            return new ResponseMessage(ResponseMessage.ERROR,"类型值错误");
        }
    }

}
